package org.dawning.shop.order.command.saga;

import lombok.extern.log4j.Log4j;
import org.axonframework.commandhandling.gateway.CommandGateway;
import org.axonframework.config.ProcessingGroup;
import org.axonframework.eventhandling.saga.EndSaga;
import org.axonframework.eventhandling.saga.SagaEventHandler;
import org.axonframework.eventhandling.saga.StartSaga;
import org.axonframework.spring.stereotype.Saga;
import org.dawning.shop.common.commands.inventory.ReserveInventoryCommand;
import org.dawning.shop.common.events.inventory.InventoryNoEnoughEvent;
import org.dawning.shop.common.events.order.OrderCancelEvent;
import org.dawning.shop.common.events.order.OrderConfirmEvent;
import org.dawning.shop.common.events.order.OrderCreateEvent;
import org.dawning.shop.common.utils.GenerateSku;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Created by miou on 2017/6/15 0015.
 */
@Saga
@Log4j
//@ProcessingGroup("shop")
public class OrderSaga {


    @Autowired
    private transient CommandGateway commandGateway;

    /**
     * 创建订单，商品库存预留
     * @param event
     */
    @StartSaga
    @SagaEventHandler(associationProperty = "orderId")
    public void on(OrderCreateEvent event){

        log.info("order create event");

        event.getOrderProducts().forEach((id, product) -> {
            String sku = GenerateSku.generateSku(product.getProductId(),product.getAttributes());
            ReserveInventoryCommand command = new ReserveInventoryCommand(
                    event.getOrderId(),sku,product.getQuantity());
            commandGateway.send(command);
        });
    }


    @SagaEventHandler(associationProperty = "orderId")
    public void on(InventoryNoEnoughEvent event){
        log.info("product inventory no enough");
    }

    /**
     * 取消订单，商品库存释放
     * @param event
     */
    @EndSaga
    @SagaEventHandler(associationProperty = "orderId")
    public void on(OrderCancelEvent event) {
        /*event.getOrderProducts().forEach((s, orderProduct) -> {
            ReleaseInventoryCommand command = new ReleaseInventoryCommand(
                    event.getOrderId(),event.getOrderProducts().get(orderProduct).getSku(),
                    event.getOrderProducts().get(orderProduct).getQuantity());
            commandGateway.send(command);
        });*/
    }

    @SagaEventHandler(associationProperty = "orderId")
    @EndSaga
    public void handle(OrderConfirmEvent event){
    }
}
